package com.wnm.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.wnm.dao.GoodsDao;
import com.wnm.dao.OrderDao;
import com.wnm.dao.OrderItemDao;
import com.wnm.dao.UserDao;
import com.wnm.pojo.Goods;
import com.wnm.pojo.Order;
import com.wnm.pojo.OrderItem;
import com.wnm.pojo.PageBean;
import com.wnm.service.OrderService;
import com.wnm.util.DBUtils;
import com.wnm.util.MallUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	GoodsDao goodsDao;
	@Autowired
	UserDao userDao;
	@Autowired
	OrderDao orderDao ;
	@Autowired
	OrderItemDao orderItemDao;
	@Override
	public void add(Order order, List<OrderItem> orderItems) {

		order.setOrderno(MallUtils.getOrderNum());
		order.setStatus(Order.PAYED);
		Goods goods = new Goods();
		// 计算总金额
		BigDecimal total = new BigDecimal("0");

		for (OrderItem orderItem : orderItems) {// 循环商品数量价格
			// 商品通过goodsDAO get商品ID
			goods = goodsDao.findGoodsByGid(orderItem.getGoodsid());
			total = total.add(goods.getSalesprice() // 通过商品ID get单价.把计算出的结果add到初始总金额中
					.multiply(new BigDecimal(String.valueOf(orderItem.getNums()))));// 用multiply来乘数量(通过订单明细get,用String.valueOf转成字符串)
			orderItem.setPrice(goods.getSalesprice());// 把单价（goods.getSalesprice()）set订单明细

		}
		order.setMoney(total);// 总价
		order.setOrdertime(MallUtils.getNow());// 下单时间通过工具类get
		orderDao.add(order);// 实体类的值添加到数据访问层
		for (OrderItem orderItem : orderItems) {// 循环商品数量价格
			orderItem.setOrderid(order.getId());// 把订单ID set到明细集合
			orderItemDao.add(orderItem);
			
		}

	}

	@Override
	public int getNumsByUserId(int userid) {
		return orderDao.getNumsByUserId(userid);

	}

	@Override
	public int getOrderByStatus(int userid,String status) {
		return orderDao.getOrderByStatus(userid,status);

	}

	@Override
	public List<Order> getOrdersByuserid(int userid) {
		return orderDao.getOrdersByuserid(userid);
		
	}

	@Override
	public PageBean<Order> findPageByuserid(int userid, int currentpage) {
		PageBean<Order> pageBean = new PageBean<Order>();
		List<Order> orders=orderDao.getOrdersByuseridAndCurrentpage(userid,(currentpage-1)*10);
		pageBean.setList(orders);
		int count=orderDao.getNumsByUserId(userid);
		pageBean.setCount(count);
		pageBean.setCurrentPage(currentpage);
		pageBean.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
		pageBean.setPageSize(10);
		
		return pageBean;
	}

	@Override
	public Order getById(int orderid) {
		PageBean<Order> pageBean = new PageBean<Order>();
		return orderDao.getById(orderid);
	}

}
